package great.project.common.oss2;

import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * <div  style="border:2px solid red;margin:20px;padding:15px;font-size:24px;text-align:center;color:green;">
 * <p>
 *  推送对象的进度监听器
 *
 *  </div>
 *
 * @author zhangshun
 * @date 2020/9/25 20:16
 */
public class PutObjectProgressListener implements ProgressListener {

    private final long totalBytes;
    private final ProgressCallback callback;
    private long bytesWritten = 0;
    private boolean succeed = false;
    private int lastPercent = -1;

    public PutObjectProgressListener(File file, ProgressCallback callback) {
        totalBytes = file.length();
        this.callback = callback;
    }

    public PutObjectProgressListener(MultipartFile file, ProgressCallback callback) {
        totalBytes = file.getSize();
        this.callback = callback;
    }

    @Override
    public void progressChanged(ProgressEvent progressEvent) {
        long bytes = progressEvent.getBytes();
        ProgressEventType eventType = progressEvent.getEventType();
        switch (eventType) {
            case REQUEST_BYTE_TRANSFER_EVENT:
                this.bytesWritten += bytes;
                int percent = (int) (this.bytesWritten * 100.0 / this.totalBytes);
                if (callback != null && this.lastPercent != percent) {
                    callback.onProgress(percent);
                    this.lastPercent = percent;
                }
                break;
            case TRANSFER_COMPLETED_EVENT:
                this.succeed = true;
                if (callback != null) {
                    callback.onProgress(101);
                }
                break;
            case TRANSFER_FAILED_EVENT:
            case TRANSFER_STARTED_EVENT:
            case REQUEST_CONTENT_LENGTH_EVENT:
            default:
                break;
        }
    }

    boolean isSucceed() {
        return succeed;
    }
}